package com.web;

import com.mysql.cj.util.StringUtils;
import com.pojo.SUser;
import com.service.IRegisterService;
import com.service.impl.RegisterServiceImpl;
import com.utils.CheckCode;
import com.utils.JdbcUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

@WebServlet("/register")
public class RegistionServlet extends HttpServlet {
    private IRegisterService service =new RegisterServiceImpl();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        /*获取jsp页面输入的值*/
        String username = request.getParameter("username");
        String psw1 = request.getParameter("psw1");
        String psw2 = request.getParameter("psw2");
        String code = request.getParameter("code");
        if(username==""){
            username=null;
        }
        SUser user = service.findInfo(username);
        /*验证用户名不为空不重复*/
        if(StringUtils.isNullOrEmpty(username)||user!=null){
            request.setAttribute("msg","用户名错误！");
            request.getRequestDispatcher("/register.jsp").forward(request,response);
        }
        /*判断两次密码是否一致*/
        if(!psw1.equalsIgnoreCase(psw2)){
            request.setAttribute("msg","两次密码不一致请重新输入！");
            request.getRequestDispatcher("/register.jsp").forward(request,response);
        }
        /*判断验证码是否正确*/
        if(!code.equalsIgnoreCase((String) request.getSession().getAttribute("code1"))){
            request.setAttribute("msg","验证码错误！");
            request.getRequestDispatcher("/register.jsp").forward(request,response);
        }
        /*注册成功添加用户*/
        else {
            String id = UUID.randomUUID().toString().replace("-","").substring(0,10);
            SUser sUser = new SUser(id, username, psw1, 1, null);
            service.addUser(sUser);
            request.setAttribute("msg1","恭喜你注册成功请前往登录！");
            request.getRequestDispatcher("/register.jsp").forward(request,response);
        }


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /*
        * 随机生成验证码
        * */
        String code1 = CheckCode.outputVerifyImage(110, 42, response.getOutputStream(), 4);
        request.getSession().setAttribute("code1",code1);
    }
}
